/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","fu/app/comm/validate","fu/app/comm/attention","oms_config/root",
	"scprit/followup/app/patientManager/addPatient.servers.js",
	"scprit/followup/app/patientManager/addPatient.ui.js",
	"scprit/followup/app/question/question.ui.js",
	"scprit/followup/app/question/question.servers.js",
	"scprit/followup/app/question/question.event.js"
	],function($,$bb,$validate,$attention,$root,$addPatientServers,$addPatientUi,$questionUi,$questionServers,$questionEvent){
	var event = {};

	var URL = $bb.baseUrl("followup");
	/**
	 * 点击关闭，跳转到工作站
	 */
	var onCloseSelect = function(){
		var config = $root.init();
		var pageParams = $bb.getPageParams();
		$bb.selectNavbar(config.route.addPatientClose);
	}
	event.onCloseSelect = function(){
		onCloseSelect();
	}
	/**
	 * 根据患者基本信息跳转到门诊录入页面
	 */
	var getPatientInfoCallback =  function(data){
		var imgSrc = 'page/followup/imgs/comm/' + (data.PatientInfo.gender == 'F'? 'girl':'boy') + '.png';
		var params = {
			patientSchemeId: data.QueueSchemeInfo.ptSchemeId,
			followQueueId: data.QueueSchemeInfo.queueId,
			patientName: data.PatientInfo.userName,
			imgSrc: imgSrc,
			queuename: data.QueueSchemeInfo.queueName,
			patientId: data.PatientInfo.id,
		};
		var config = $root.init();
		$bb.openPage(config.route.addPatientJump,params);
	}
	/**
	 * 保存成功后的回调函数
	 */
	var getSaveBuildCallback =  function(data){
		var pageParams = $bb.getPageParams();
		$addPatientServers.bindHisIdAndPatientId(data, pageParams.pat1, function () {
			$bb.toastShow("添加成功！",2000);
			$addPatientServers.ajaxPatientInfo(data, getPatientInfoCallback);
		})
	}
	/**
	 * 点击保存按钮
	 */
	var onSaveClick = function(params){
		var patientName = $("#questionDetail form").find("input[name='Pub1100002']").val();
        var formId = $("#questionDetail form").attr("id");
        var questiones = $questionServers.getDataForDom(formId);
        $addPatientServers.ajaxSaveBuildQuestions(params,patientName,questiones,getSaveBuildCallback);
	}
	/**
	 * 表单提交前的校验
	 */
	var onValidateClick = function(){
		var params = $(this).data("params");
		if( $validate.init() ){
		    onSaveClick(params);
		}
	}
	/**
	 * 建档问卷请求成功会后的回调函数
	 */
	var getBuildQuestCallback = function(data,params,values){
		$questionUi.init({
            id: "questionDetail",
            list: data.questiones,
            showIcon: true,
            values: values,
            initParams:{
            	queueId:params.queueId
            }
        });
        $questionEvent.init({
	        "getPatientsByPhone":{
	        	params:params,
	        	callback:buildQuestions
	        },
	        "getGeneFusion":{
				"followQueueId":params.queueId,
				"values":values
			}
        });
        $attention.init();
        $('.validatebox').data("attentionFun",$attention.blurInit);	// 校验之前提示警告
		$validate.blurInit();
        var config = $root.init();
        var topbars = [
			{
				"icon":"fa fa-floppy-o",
				"name":"保存",
				"callback":onValidateClick,
				"params":params
			}
		];
		if( config.dom.addPatientClose ){
			topbars.push({
					"icon":"fa fa-times",
					"name":"关闭",
					"callback":onCloseSelect,
			});
		}
		$bb.toolbar(topbars);
	}
	/**
	 * 建档问卷
	 */
	var buildQuestions = function(params,result){
		$addPatientServers.ajaxBuildQuestions(params,getBuildQuestCallback,result.values);
	}
	/**
	 * 建档问卷
	 */
	var bookbuilding = function(params){
		$addPatientUi.tit({
			id: "queueName",
			queueName: params.queueName
		});
		buildQuestions(params,{"values":null});
	}
	/**
	 * 点击队列card
	 */
	event.onQueueNavSelect = function(){
		$(this).addClass("active").siblings().removeClass("active");
		var queueName = $(this).find(".queue-name").text();
		var queueId = $(this).attr("queueId");
		var schemeId = $(this).attr("schemeId");
		var params = {
			"queueName":queueName,
			"queueId":queueId,
			"schemeId":schemeId
		};
		bookbuilding(params);
	}

	/**
	 * 渲染 His 系统过来的数据
	 * @param { object } params
	 */
	 event.is_render = false
	 event.renderHisData = function (params) {
		 for (var i = 0; i < $('.queue-card').length; i++) {
			 var dom = $('.queue-card')[i]
			 if ($(dom).attr('queueid') == params.queueid) {
				 $(dom).click()
			 }
		 }
		 // 渲染数据
		 function renderDataToDom() {
			 setTimeout(function () {
				 if ($('input[name=Pub1100001]')) {
					 renderData(params)
				 } else {
					 renderDataToDom()
				 }
			 }, 1000)
		 }
		 renderDataToDom()
	 }

	 function renderData(params) {
		// console.log(params)
		// 姓名
		$('input[name=Pub1100002]').val(params.pat6)
		// 手机号
		$('input[name=Pub1100001]').val(params.pat5)
		// 性别
		if (params.hasOwnProperty('pat10') && params.pat10 == 0) {
			$('.radio-inline')[0].click()
		} else {
			$('.radio-inline')[1].click()
		}
		// 出生日期
		$('input[name=Pub1100004]').val(params.pat11.split(' ')[0])
		// 预产期
		$('input[name=Pub1100005]').val(params.pat13.split(' ')[0])
		// 孕周
		// $('input[name=Pub1100005]').val(params.pat13.split(' ')[0])
		// 出生体重
		$('input[name="jdtzjd_cstz"]').val(params.pat14)
		$('input[name="zcejd_cstz"]').val(params.pat14)

		// 住院号
		$('input[name="Pub12x00008"]').val(params.pat4)
		// 父亲姓名
		$('input[name="jdtzjd_fqxm"]').val(params.pat8)
		$('input[name="zcejd_fqxm"]').val(params.pat8)

		// 母亲姓名
		$('input[name="jdtzjd_mqxm"]').val(params.pat7)
		$('input[name="zcejd_mqxm"]').val(params.pat7)

		// 居住地
		$('input[name="jdtzjd_jzd"]').val(params.pat9)
		$('input[name="zcejd_jtzz"]').val(params.pat9)

		// 出院身长
		$('input[name="zcejd_cysc"]').val(params.pat20)

		// 出院头围
		$('input[name="zcejd_cysc"]').val(params.pat21)

		// 家庭地址
		$('input[name="jd_jtdz"]').val(params.EMR.pat9)

		// 主诉
		$('textarea[name="jd_zhusu"]').val(params.EMR.emr1)

		// 现病史
		$('textarea[name="jd_xianbs"]').val(params.EMR.emr2)

		// 既往史
		$('textarea[name="jd_jiws"]').val(params.EMR.emr3)

		// 个人史
		$('textarea[name="jd_gerens"]').val(params.EMR.emr4)

		// 家族史
		$('textarea[name="jd_jiazs"]').val(params.EMR.emr5)

		// 初步诊断
		$('textarea[name="jd_chubuzd"]').val(params.EMR.emr6)

		// 出院诊断
		$('textarea[name="jd_chuyzd"]').val(params.EMR.emr7)

		event.is_render = true
	}



	/**
	 * 自动计算住院天数
	 */
	$('.content-main').on('blur', 'input[name=zcejd_ruyrq]', function () {
		computeDays();
	});
	$('.content-main').on('blur', 'input[name=Pub13x00010]', function () {
		computeDays();
	});
	function computeDays() {
		var enterDate = $('input[name=zcejd_ruyrq]').val();
		var outDate = $('input[name=Pub13x00010]').val();
		if (!enterDate || !outDate) return
		enterDate = new Date(enterDate).getTime();
		outDate = new Date(outDate).getTime();
		var reduce = Math.floor(outDate / 1000) - Math.floor(enterDate / 1000);
		var oneDay = 3600 * 24;
		var day = Math.ceil(reduce / oneDay);
		$('input[name=zcejd_zyts]').val(day);
	}

	/**
	 * 自动计算体重增长
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cstz]', function () {
		computeWeight();
		getPValue('00001', $('input[name=zcejd_cstz]').val(), 0, 'zcejd_tzpz');
	});
	$('.content-main').on('blur', 'input[name=zcejd_cytz]', function () {
		computeWeight();
		getPValue('00001', $('input[name=zcejd_cytz]').val(), getDiffDays(), 'zcejd_cytzpz');
	});
	function computeWeight() {
		var before = $('input[name=zcejd_cstz]').val();
		var after = $('input[name=zcejd_cytz]').val();
		var val = after - before
		$('input[name=zcejd_cytzzz]').val(val);
	}

	/**
	 * 获取出生身长
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cssc]', function () {
		getPValue('00002', $('input[name=zcejd_cssc]').val(), 0, 'zcejd_scpz');
	});

	/**
	 * 获取出生头围
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cstw]', function () {
		getPValue('00003', $('input[name=zcejd_cstw]').val(), 0, 'zcejd_twpz');
	});

	/**
	 * 获取出院身长
	 */
	 $('.content-main').on('blur', 'input[name=zcejd_cysc]', function () {
		getPValue('00002', $('input[name=zcejd_cysc]').val(), getDiffDays(), 'zcejd_cyscpz');
	});

	/**
	 * 获取出院头围
	 */
	 $('.content-main').on('blur', 'input[name=zcejd_cytw]', function () {
		getPValue('00003', $('input[name=zcejd_cytw]').val(), getDiffDays(), 'zcejd_cytwpz');
	});

	/**
	 * 获取出生时的 p 值
	 * @param { string } type
	 * @param { string } val
	 */
	function getPValue(type, val, age, target) {
		var gender = $('input[name=Pub1100003]:checked').val();
		if (!type || !val || !gender) return
		if (age !=0 && !age) return
		gender = gender == '男' ? "N" : "F";
		$bb.ajax({
			url: URL + 'followup/service/patient/growth/getPercentiles',
			data: JSON.stringify({ data:
				{
					type: type,
					gender: gender,
					age: age,
					value: val
				}
			}),
			success: function (res) {
				console.log($(`input[name=${ target }]`))
				if (res.data.percentiles == '<3%') {
					$(`select[name=${ target }]`).val('<P3');
				} else if (res.data.percentiles == '>97%') {
					$(`select[name=${ target }]`).val('>P97');
				} else {
					$(`select[name=${ target }]`).val('P3～P97');
				}
			}
		})
	}

	function getDiffDays() {
		var birth = $('input[name=Pub1100004]').val();
		var target = $('input[name=Pub13x00010]').val();
		if (!birth || !target) return 0
		birth = Math.floor(new Date(birth).getTime() / 1000);
		target = Math.floor(new Date(target).getTime() / 1000);
		var day = 3600 * 24;
		var reduce = Math.ceil((target - birth) / day);
		console.log(reduce)
		return reduce;
	}

	return event;
});
